<template>
  <view
    :style="{ direction: $t('dir') }"
    :class="$t('dir') == 'rtl' ? 'rtl' : 'ltr'"
  >
    <navbar
      :title="$t('my')"
      :back="false"
      bgLayer="linear-gradient(#c8d5ec, #fff)"
      navbarBg="linear-gradient(#c8d5ec, #dae3f2)"
    >
 
    </navbar>
    <view class="main">

        <x-drag />
      <!-- 头像 -->
      <view  class="row items-center justify-between topbox">
        <view class="row items-center pa-md" >
          <view class="avatar-container">
            <u-image
              :src="
                userInfo.avatar
                  ? userInfo.avatar
                  : '/static/images/my/default-avatar.png'
              "
              width="118rpx"
              height="118rpx"
              radius="50%"
              :lazy-load="true"
              mode="aspectFill"
            />
          </view>
          <view class="px-sm">
            <view class="fs-md row items-center">
              <view
                class="nickname text-nowrap"
                style="max-width: 270rpx"
                :class="'dir-' + $tools.strDir(userInfo.nickname)"
              >
                {{
                  userInfo.nickname ||
                  ($t("dir") == "rtl" ? " تەڭشەلمىگەن" : "未设置")
                }}
              </view>
            </view>
            <view class="fs-md" style="color: #8d8d8d">
              <view class="fs-xs">
                <view
                  >Tel:
                  {{
                    userInfo.mobile ||
                    ($t("dir") == "rtl" ? " تەڭشەلمىگەن" : "未设置")
                  }}</view
                >
                <view class="id">ID: {{ userInfo.id }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="row items-center mx-md">
          <!-- <image class="mx-sm" src="/static/images/my/scan.png" style="width: 50rpx; height: 50rpx" mode="scaleToFill" /> -->
          <image
            class="mx-md"
            src="/static/images/my/setting.png"
            style="width: 50rpx; height: 50rpx"
            mode="scaleToFill"
            @click="showEditPopup = true"
          />
        </view>
      </view>


      <!-- ئۇچۇر تەھرىرلەش تىزىملىكى -->
      <u-popup :show="showEditPopup" mode="center" width="600rpx" height="auto" @close="showEditPopup = false" :customStyle="{
        borderRadius: '52rpx'
      }">
        <view class="edit-popup">
          <view class="user-profile">
            <view class="profile-avatar">
              <u-image
                :src="userInfo.avatar ? userInfo.avatar : '/static/images/my/default-avatar.png'"
                width="160rpx"
                height="160rpx"
                radius="50%"
                mode="aspectFill"
              />
              <button
                class="avatar-overlay"
                open-type="chooseAvatar"
                @chooseavatar="onChooseAvatar"
                :disabled="isUploading"
              >
                <u-icon name="camera-fill" color="#fff" size="32"></u-icon>
              </button>
            </view>
            <view class="profile-info">
              <view class="profile-name">
                <input 
                  type="nickname"
                  class="profile-input"
                  :placeholder="$t('dir') == 'rtl' ? 'ئىسمىڭىزنى كىرگۈزۈڭ' : '请输入昵称'"
                  v-model="userInfo.nickname"
                  
                />
              </view>
              <view class="profile-phone">
                <input 
                  type="number"
                  v-model="userInfo.mobile"
                  :placeholder="$t('dir') == 'rtl' ? 'تېلېفون نومۇرىڭىزنى كىرگۈزۈڭ' : '请输入手机号'"
                  class="profile-input"
                  maxlength="11"
  
                />
              </view>
            </view>
          </view>
          <view class="popup-footer">
            <text class="cancel-btn" @click="saveUserInfo">
              {{ $t("dir") == "rtl" ? "ساقلاش" : "保存" }}
            </text>
          </view>
        </view>
      </u-popup>

      <view class=" bg-white bg-white rounded-26 mx-sm">
        <view class="mawuya row items-center justify-between mx-sm py-sm px-md">
          <view
            v-for="(item, i) in menutItems"
            :key="i"
            class="text-center button mt-xs"
            @click="menutItemsClick(item)"
          >
            <image
              :src="`/static/images/my/${item.img}.png`"
              mode="scaleToFill"
              style="width: 54rpx; height: 54rpx"
            />
            <view>{{ $t(item.k) }}</view>
          </view>
        </view>

        <!-- 其他 -->
        <view style="border-radius: 20rpx; padding: 32rpx 0 16rpx 0">
          <view
            v-for="(item, index) in otherItems"
            :key="index"
            @click="otherItemsClick(item)"
            class="row items-center other-items"
          >
            <u-image
              :src="'/static/images/my/' + item.img"
              width="34rpx"
              height="34rpx"
              :lazy-load="true"
              mode="scaleToFill"
            />
            <view style="margin: 0 20rpx">{{ item["name" + $t("k")] }} </view>
            <view
              v-if="item.id == 6"
              style="color: #7a7a7a"
              :style="{
                marginRight: $t('key') == 'ug' ? 'auto' : 0,
                marginLeft: $t('key') == 'zh' ? 'auto' : 0,
              }"
              class="fs-sm row items-center"
            >
              <text class="mx-xs" :class="{ 'text-red': $t('key') == 'ug' }"
                >ئۇ</text
              >|
              <text
                class="mx-xs mt-xs"
                :class="{ 'text-red': $t('key') == 'zh' }"
                >中</text
              >
            </view>
          </view>
        </view>
        <!-- navigationes -->
        <view class="text-center mt-lg fs-md" style="color: #7a7a7a"
          >كورلا ئۇچۇر سۇپىسى</view
        >
        <view class="dir-ltr mt-md" style="margin-bottom: 120rpx">
          <u-swiper
            v-if="bannerList && bannerList.length > 0"
            :list="bannerList"
            :indicator="true"
            circular
            keyName="img"
            previousMargin="0"
            nextMargin="0"
            height="126rpx"
            @click="tapBanner"
            :duration="500"
            :interval="3000"
            indicatorActiveColor="#DFDFDF"
            indicatorInactiveColor="#FFFFFF"
          >
          </u-swiper>
        </view>
      </view>
    </view>
    <view class="deep"></view>

    <!--  客服弹出层  -->
    <help-popup
      :show="helpPopupShow"
      @close="helpPopupShow = false"
      :qrCode="settingData.qrcode"
    />

    <!-- 底部导航栏 -->
    <tabbar
      :activeTab="4"
      :unreadCount="unreadCount"
      :unreadNoticeCount="unreadNoticeCount"
      :showHideRegion="false"
    />
  </view>
</template>

<script>
// 引入配置
import config from "@/utils/config";
const app = getApp();
export default {
  computed: {},
  watch: {},
  data() {
    return {
      qrpShow: false,
      codeUrl: "",
      baseUrl: config.baseUrl,
      bannerList: [],
      downloadNum: null,
      showdownLine: false,
      userInfo: {},

      myViewAndApplyAgent: [
        {
          img: "/app-imgs/my/view.png",
          imgUg: "/app-imgs/my/view_ug.png",
        },
        {
          img: "/app-imgs/my/seller-agent.png",
          imgUg: "/app-imgs/my/seller-agent_ug.png",
        },
      ],

      menutItems: [
        { id: 1, k: "wodefasong", img: "view-home"},
        { id: 2, k: "wodeguankan", img: "view"},
        { id: 3, k: "wodeshoucang", img: "fav" },
      ],
      otherItems: [
        {
          id: 6,
          name_ug: "تىل تاللاش",
          name: "切换语言",
          img: "language.png",
        },
        {
          id: 4,
          name_ug: "تەكلىپ-پىكىر",
          name: "反馈",
          img: "Headphone.png",
        },
        {
          id: 5,
          name_ug: "تەڭشەك",
          name: "设置",
          img: "Settings.png",
          url: "/pages/settings/index",
        },
      ],

      helpPopupShow: false, //客服弹出层
      unreadCount: 0,
      unreadNoticeCount: 0,

      settingData: {
        qrcode: "",
        iosVersion: "",
      },

      showUserProfilePopup: false,
      showEditPopup: false,
      showAvatarPopup: false,
      showNicknamePopup: false,
      showPhonePopup: false,
      tempAvatar: null,
      tempNickname: "",
      tempUserInfo: {
        avatar: '',
        nickname: '',
        mobile: ''
      },
      isUploading: false,
    };
  },
  onLoad() {
    this.userInfo = uni.getStorageSync("user");
  },
  onShow() {
    uni.setNavigationBarTitle({
      title: this.$t("my"),
    });
  },
  onPullDownRefresh() {
    uni.stopPullDownRefresh();
  },
  methods: {
          otherItemsClick(item) {
            console.log('item.id',item.id)
            if (item.id == 4 ) {
              uni.navigateTo({
                url:'/pages/my/pikir'
              })
                return
            }
            if (item.id == 5 ) {
              this.showEditPopup = true
                return
            }
            if (item.id == 6) {
                this.switchLang()
                return
            }
        },
    // سۈرەت تاللاش
    async onChooseAvatar(e) {
      if (e.detail.avatarUrl && !this.isUploading) {
        this.isUploading = true;
        uni.showLoading({
          title: this.$t("dir") == "rtl" ? "يۈكلىنىۋاتىدۇ..." : "上传中...",
        });

        try {
          const openid = uni.getStorageSync('openid');
          const uploadRes = await this.$tools.uploadFile("/upload_avatar", e.detail.avatarUrl);

          if (uploadRes.code === 200) {
            this.tempUserInfo.avatar = uploadRes.list.data.fullUrl;
            this.userInfo.avatar = uploadRes.list.data.fullUrl;
            uni.showToast({
              title: this.$t("dir") == "rtl" ? "سۈرەت تاللاندى" : "已选择图片",
              icon: "success",
            });
          }
        } catch (err) {
          console.log(err)
          uni.showToast({
            title: this.$t("dir") == "rtl" ? "مەغلۇپ بولدى" : "上传失败",
            icon: "none",
          });
        } finally {
          uni.hideLoading();
          this.isUploading = false;
        }
      }
    },

    // ئىسىم تاللاش
    async getNickname(e) {
      if (e.detail.nickname) {
        this.tempUserInfo.nickname = e.detail.nickname;
        this.userInfo.nickname = e.detail.nickname;
        uni.showToast({
          title: this.$t("dir") == "rtl" ? "ئىسىم تاللاندى" : "已选择昵称",
          icon: "success",
        });
      }
    },

    // تېلېفون نومۇر ساقلاش
    async submitPhoneNumber() {
      if (this.userInfo.mobile) {
        this.tempUserInfo.mobile = this.userInfo.mobile;
        uni.showToast({
          title: this.$t("dir") == "rtl" ? "نومۇر كىرگۈزۈلدى" : "已输入号码",
          icon: "success",
        });
      }
    },

    // ئۇچۇرلارنى ساقلاش
    async saveUserInfo() {
      uni.showLoading({
        title: this.$t("dir") == "rtl" ? "ساقلىنىۋاتىدۇ..." : "保存中...",
      });

      try {
        const updateData = {
          avatar: this.userInfo.avatar || '',
          nickname: this.userInfo.nickname || '',
          mobile: this.userInfo.mobile || ''
        };

        const updateRes = await this.$uniapi("/edit_member_list", updateData);

        if (updateRes.code === 200) {
          uni.setStorageSync("user", this.userInfo);
          uni.showToast({
            title: this.$t("dir") == "rtl" ? "مۇۋەپپەقىيەتلىك ساقلاندى" : "保存成功",
            icon: "success",
          });
          this.showEditPopup = false;
        }
      } catch (err) {
        console.log(err);
        uni.showToast({
          title: this.$t("dir") == "rtl" ? "مەغلۇپ بولدى" : "保存失败",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    menutItemsClick(item) {
     uni.navigateTo({
      url:'/pages/my/save?id=' + item.id
     })
    },

    switchLang(lang) {
      if (!lang) lang = uni.getStorageSync("lang") == "ug" ? "zh" : "ug";
      this._i18n.locale = lang;
      uni.setStorageSync("lang", lang);
      uni.reLaunch({
        url: "/pages/my/index",
      });
    },

    tapBanner(e) {
      console.log("banner", e);
      const adId = this.bannerList[e].id;
      uni.navigateTo({
        url: "/pages/index/bannerDetail?id=" + adId,
      });
    },

    myViewAndApplyAgentOnClikc(index) {
      if (index == 0) this.goPath("/pages/my-list/view");
      else if (index == 1) {
        let url = "/pages/integral/integral";
        this.goPath(url);
      }
    },

    settingsClick(index, url) {
      if (index == 0) {
        this.switchLang();
        return;
      }
      this.goPath("/pages/" + url);
    },

    formatDate(timestamp) {
      const date = new Date(timestamp * 1000);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1并补齐两位
      const day = String(date.getDate()).padStart(2, "0"); // 需要补齐两位
      return `${year}-${month}-${day}`;
    },

    openAvatarEdit() {
      this.showEditPopup = false;
      this.showAvatarPopup = true;
    },

    openNicknameEdit() {
      this.showEditPopup = false;
      this.tempNickname = this.userInfo.nickname || "";
      this.showNicknamePopup = true;
    },

    openPhoneEdit() {
      this.showEditPopup = false;
      this.showPhonePopup = true;
    },

    cancelAvatarEdit() {
      this.showAvatarPopup = false;
      this.showEditPopup = true;
    },


    cancelNicknameEdit() {
      this.showNicknamePopup = false;
      this.showEditPopup = true;
    },


  },
};
</script>

<style lang="scss" scoped>
.topbox{
  background: linear-gradient( #dae3f2,#c8d5ec);
  direction: ltr;
  border-radius: 0 0 50rpx 50rpx ;
}
.other-items {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f3f3f3;
  margin: 0 36rpx;
}
.id{
  background: #3a8ce6;
  display: inline;
  padding: 4rpx 10rpx;
  border-radius: 10px;
  color: #fff !important;
  font-size:10px !important;
}
.other-items:last-child {
  border: none;
}
.deep {
  height: 180rpx;
}

.avatar-container {
  position: relative;
  margin-bottom: 20rpx;
  
  .u-image {
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  }
}

.px-sm {
  .fs-md {
    margin-bottom: 16rpx;
    
    .nickname {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .fs-xs {
    view {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 8rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.mx-md {
  image {
    padding: 10rpx;
    border-radius: 50%;
    background: #f5f7fa;
    transition: all 0.3s;

    &:active {
      background: #eef0f3;
    }
  }
}

.login-btn {
  padding: 10rpx 30rpx;
  background: #3a8ce6;
  color: #fff;
  border-radius: 30rpx;
  font-size: 28rpx;
}

.user-profile-popup {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;

  .popup-title {
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
  }

  .popup-content {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    margin-bottom: 30rpx;

    button {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      font-size: 28rpx;
      border: none;

      &.wechat-btn {
        background: #07c160;
        color: #fff;
      }

      &.phone-btn {
        background: #3a8ce6;
        color: #fff;
      }
    }
  }

  .popup-footer {
    text-align: center;

    .cancel-btn {
      color: #999;
      font-size: 28rpx;
    }
  }
}

.edit-popup {
  padding: 0;
  border-radius: 24rpx;
  overflow: hidden;
  background: #fff;
  width: 85vw;
  border-radius:50rpx ;
  .user-profile {
    padding: 40rpx;
    background: linear-gradient(180deg, #f0f3f9 0%, #ffffff 100%);
    text-align: center;

    .profile-avatar {
      position: relative;
      display: inline-block;
      margin-bottom: 30rpx;
      
      .avatar-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.3);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        padding: 0;
        margin: 0;
        opacity: 0;
        transition: opacity 0.3s;

        &::after {
          border: none;
        }

        &:active {
          opacity: 0.8 !important;
        }
      }

      &:hover {
        .avatar-overlay {
          opacity: 1;
        }
      }
    }

    .profile-info {
      .profile-name, .profile-phone {
        margin: 0 auto;
        width: 70%;
        margin-bottom: 20rpx;
      }

      .profile-input {
        width: 100%;
        height: 80rpx;
        line-height: 80rpx;
        background: #e9f2ff;
        border-radius: 40rpx;
   
        font-size: 28rpx;
        color: #333;
        text-align: center;
        border: none;

        &::placeholder {
          color: #999;
        }

        &:focus {
          background: #fff;
          box-shadow: 0 0 0 2rpx #000 inset;
        }
      }

      button.profile-input {
        margin: 0;
        font-weight: normal;
        
        &::after {
          border: none;
        }
      }
    }
  }

  .popup-footer {
    text-align: center;
    padding: 30rpx;
    background: #fff;

    .cancel-btn {
      display: inline-block;
      padding: 20rpx 120rpx;
      background: #000;
      color: #fff;
      font-size: 32rpx;
      border-radius: 40rpx;
      font-weight: 500;
    }
  }
}

.mawuya {
  margin: 30rpx 0 0;
  border-radius: 32rpx;
  background: #ffffff;
  box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.076);
  overflow: hidden;
  padding: 20rpx;
  

  

}
</style>